#! /usr/bin/python
# Main program for plotting vector fields in gnuplot
from myvector import *

# settings for the plot
xrange_l = -2.
xrange_u =  2.

yrange_l = -2.
yrange_u =  2.

step = 0.25

# length of the arrows
vector_length = 0.95 * step

#################### definition of the vector field ########################
# Here you can define your vectorfield. I did this in an external file and
# import the functions
from myvectorfield import *
# See myvectorfield.py for further instructions

############################ MAIN PROGRAM ##################################

# compute the bins that are needed to
max_c_x = int((xrange_u - xrange_l) / step)
max_c_y = int((yrange_u - yrange_l) / step)


# compute the vector field
pos = []
field = []
for x in range(max_c_x):
	for y in range(max_c_y):
		r = vector(x*step - max_c_x/2. * step  ,y*step - max_c_y/2. * step, 0.)

		v_field = vectorfield(r)

		pos.append(r)
		field.append(v_field)

# comppute the largest absolute value
large_val = 0.
for i in range(len(pos)):
	temp = field[i].abs()
	if temp > large_val: large_val = temp

# normalize largest value to the desired vector_length and save everything to a file
liste = []
for i in range(len(pos)):
	n = field[i] * (vector_length/large_val)			# normalize largest vector to one

	liste.append("%.3f\t%.3f\t%.3f\t%.3f\n" % (pos[i].x, pos[i].y, n.x, n.y))


f = open("data.dat", "w")
f.writelines(liste)
f.close()

import os

f = open("plot.gnu", "w")
f.write("""
set xrange [%.2f:%.2f]
set yrange [%.2f:%.2f]
set xlabel "x"
set ylabel "y"

set key below

plot "data.dat" title "%s" w vec

pause -1
""" % (xrange_l, xrange_u, yrange_l, yrange_u, plot_title))
f.close()

os.system("gnuplot plot.gnu")
